package com.daluzy.chmanager.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cazaea.sweetalert.SweetAlertDialog;
import com.daluzy.chmanager.R;
import com.daluzy.chmanager.bean.Account;
import com.daluzy.chmanager.bean.Employee;
import com.daluzy.chmanager.bean.School;
import com.daluzy.chmanager.bean.Students;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

public class RegisterActivity extends AppCompatActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.radio_student)
    RadioButton radioStudent;
    @BindView(R.id.radio_employee)
    RadioButton radioEmployee;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.et_student_name)
    EditText etStudentName;
    @BindView(R.id.et_student_num)
    EditText etStudentNum;
    @BindView(R.id.et_student_phone)
    EditText etStudentPhone;
    @BindView(R.id.radio_btn_male)
    RadioButton radioBtnMale;
    @BindView(R.id.radio_btn_female)
    RadioButton radioBtnFemale;
    @BindView(R.id.radio_group_sex)
    RadioGroup radioGroupSex;
    @BindView(R.id.et_student_grade)
    EditText etStudentGrade;
    @BindView(R.id.et_student_speciality)
    EditText etStudentSpeciality;
    @BindView(R.id.et_student_place)
    EditText etStudentPlace;
    @BindView(R.id.et_student_class)
    EditText etStudentClass;
    @BindView(R.id.et_student_department)
    EditText etStudentDepartment;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_password_again)
    EditText etPasswordAgain;
    @BindView(R.id.btn_register_student)
    Button btnRegisterStudent;
    @BindView(R.id.ll_student)
    LinearLayout llStudent;
    @BindView(R.id.et_employee_name)
    EditText etEmployeeName;
    @BindView(R.id.et_employee_phone)
    EditText etEmployeePhone;
    @BindView(R.id.radio_btn_employee_male)
    RadioButton radioBtnEmployeeMale;
    @BindView(R.id.radio_btn_employee_female)
    RadioButton radioBtnEmployeeFemale;
    @BindView(R.id.radio_group_employee_sex)
    RadioGroup radioGroupEmployeeSex;
    @BindView(R.id.et_password_employee)
    EditText etPasswordEmployee;
    @BindView(R.id.et_password_again_employee)
    EditText etPasswordAgainEmployee;
    @BindView(R.id.btn_register_employee)
    Button btnRegisterEmployee;
    @BindView(R.id.ll_employee)
    LinearLayout llEmployee;
    @BindView(R.id.ll_edit)
    LinearLayout llEdit;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_student_school)
    TextView tvStudentSchool;
    @BindView(R.id.tv_employee_school)
    TextView tvEmployeeSchool;
    private String studentSex = "男";
    private String employeeSex = "男";
    private LoadingDialog loadingDialog;
    private School school;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_daluzy);
        ButterKnife.bind(this);
        loadingDialog = new LoadingDialog(this);
        radioGroup.check(R.id.radio_student);
        llStudent.setVisibility(View.VISIBLE);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radio_student) {
                llStudent.setVisibility(View.VISIBLE);
                llEmployee.setVisibility(View.GONE);
            } else {
                llStudent.setVisibility(View.GONE);
                llEmployee.setVisibility(View.VISIBLE);
            }
        });
        radioGroupSex.check(R.id.radio_btn_male);
        radioGroupEmployeeSex.check(R.id.radio_btn_employee_male);
        radioGroupSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_btn_male) {
                    studentSex = "男";
                } else {
                    studentSex = "女";
                }
            }
        });
        radioGroupEmployeeSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_btn_employee_male) {
                    employeeSex = "男";
                } else {
                    employeeSex = "女";
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.btn_register_student, R.id.btn_register_employee, R.id.tv_student_school, R.id.tv_employee_school})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_student_school:
                Intent intent = new Intent(RegisterActivity.this, SelectSchoolActivity.class);
                startActivityForResult(intent, 2021);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_register_student:
                btnRegisterStudent.setEnabled(false);
                studentCheck();
                break;
            case R.id.btn_register_employee:
                btnRegisterEmployee.setEnabled(false);
                employeeCheck();
                break;
        }
    }

    private void studentCheck() {

        String studentName = etStudentName.getText().toString().trim();
        String studentNum = etStudentNum.getText().toString().trim();
        String studentGrade = etStudentGrade.getText().toString().trim();
        String studentSpe = etStudentSpeciality.getText().toString().trim();
        String studentPlace = etStudentPlace.getText().toString().trim();
        String studentClass = etStudentClass.getText().toString().trim();
        String studentDepartment = etStudentDepartment.getText().toString().trim();
        String studentPhone = etStudentPhone.getText().toString().trim();
        String studentPassword = etPassword.getText().toString().trim();
        String studentPasswordAgain = etPasswordAgain.getText().toString().trim();

        if (TextUtils.isEmpty(studentName)) {
            Toast.makeText(RegisterActivity.this, "请输入姓名", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentNum)) {
            Toast.makeText(RegisterActivity.this, "请输入学号", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentPhone)) {
            Toast.makeText(RegisterActivity.this, "请输入电话号码", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentGrade)) {
            Toast.makeText(RegisterActivity.this, "请输入所在年级", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentSpe)) {
            Toast.makeText(RegisterActivity.this, "请输入所学专业", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentPlace)) {
            Toast.makeText(RegisterActivity.this, "请输入籍贯", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentClass)) {
            Toast.makeText(RegisterActivity.this, "请输入所在班", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentDepartment)) {
            Toast.makeText(RegisterActivity.this, "请输入所在院系", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentPassword)) {
            Toast.makeText(RegisterActivity.this, "请输入登录密码", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentPasswordAgain)) {
            Toast.makeText(RegisterActivity.this, "请再次输入密码", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (!studentPassword.equals(studentPasswordAgain)) {
            Toast.makeText(RegisterActivity.this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
            btnRegisterStudent.setEnabled(true);
            return;
        }
        if (school == null) {
            Toast.makeText(RegisterActivity.this, "请选择学校", Toast.LENGTH_SHORT).show();
            btnRegisterEmployee.setEnabled(true);
            return;
        }
        if (loadingDialog != null) {
            loadingDialog.show();
        }
        Students students = new Students();
        students.setAccount(studentPhone);
        students.setStudent_class(studentClass);
        students.setStudent_department(studentDepartment);
        students.setStudent_grade(studentGrade);
        students.setStudent_id(studentNum);
        students.setStudent_name(studentName);
        students.setStudent_phone(studentPhone);
        students.setStudent_place(studentPlace);
        students.setStudent_sex(studentSex);
        students.setStudent_speciality(studentSpe);
        students.setStudent_school(school.getSchool_id());
        Account account = new Account();
        account.setAccount(studentPhone);
        account.setPassword(studentPassword);
        checkAccount(students, account);

    }

    private void studentRegister(Students students, Account account) {
        new Thread(() -> students.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                runOnUiThread(() -> {
                    if (e == null) {
                        createAccount(account);
                    } else {
                        btnRegisterStudent.setEnabled(true);
                        Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        if (loadingDialog != null) {
                            loadingDialog.close();
                        }
                    }
                });
            }
        })).start();


    }

    private void checkAccount(Students students, Account account) {
        if (loadingDialog != null)
            loadingDialog.show();
        BmobQuery<Account> query = new BmobQuery<>();
        query.addWhereEqualTo("account", account.getAccount());
        query.order("-createdAt")
                .findObjects(new FindListener<Account>() {
                    @Override
                    public void done(List<Account> object, BmobException e) {
                        if (e == null) {
                            if (object != null && object.size() > 0) {
                                Toast.makeText(RegisterActivity.this, "该账号已存在，请检查您输入的电话号码", Toast.LENGTH_SHORT).show();
                                if (loadingDialog != null)
                                    loadingDialog.close();
                            } else {
                                studentRegister(students, account);
                            }

                        } else {
                            Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            if (loadingDialog != null)
                                loadingDialog.close();
                        }
                        btnRegisterEmployee.setEnabled(true);
                        btnRegisterStudent.setEnabled(true);
                    }
                });
    }

    private void createAccount(Account account) {
        new Thread(() -> account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                runOnUiThread(() -> {
                    if (loadingDialog != null) {
                        loadingDialog.close();
                    }
                    if (e == null) {
                        Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    btnRegisterStudent.setEnabled(true);
                    btnRegisterEmployee.setEnabled(true);
                });

            }
        })).start();


    }

    private void employeeCheck() {

        String employeeName = etEmployeeName.getText().toString().trim();
        String employeePhone = etEmployeePhone.getText().toString().trim();
        String employeePassword = etPasswordEmployee.getText().toString().trim();
        String employeePasswordAgain = etPasswordAgainEmployee.getText().toString().trim();

        if (TextUtils.isEmpty(employeeName)) {
            Toast.makeText(RegisterActivity.this, "请输入姓名", Toast.LENGTH_SHORT).show();
            btnRegisterEmployee.setEnabled(true);
            return;
        }

        if (TextUtils.isEmpty(employeePhone)) {
            Toast.makeText(RegisterActivity.this, "请输入电话号码", Toast.LENGTH_SHORT).show();
            btnRegisterEmployee.setEnabled(true);
            return;
        }

        if (TextUtils.isEmpty(employeePassword)) {
            Toast.makeText(RegisterActivity.this, "请输入登录密码", Toast.LENGTH_SHORT).show();
            btnRegisterEmployee.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(employeePasswordAgain)) {
            Toast.makeText(RegisterActivity.this, "请再次输入密码", Toast.LENGTH_SHORT).show();
            btnRegisterEmployee.setEnabled(true);
            return;
        }
        if (!employeePassword.equals(employeePasswordAgain)) {
            Toast.makeText(RegisterActivity.this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
            btnRegisterEmployee.setEnabled(true);
            return;
        }

        if (loadingDialog != null) {
            loadingDialog.show();
        }
        Employee employee = new Employee();

        employee.setAccount(employeePhone);
        employee.setEmployee_id(String.valueOf(System.currentTimeMillis()));
        employee.setEmployee_name(employeeName);
        employee.setEmployee_phone(employeePhone);
        employee.setEmployee_sex(employeeSex);


        Account account = new Account();
        account.setAccount(employeePhone);
        account.setPassword(employeePassword);

        checkAccount(employee, account);
    }

    private void checkAccount(Employee employee, Account account) {
        if (loadingDialog != null)
            loadingDialog.show();
        BmobQuery<Account> query = new BmobQuery<>();
        query.addWhereEqualTo("account", account.getAccount());
        query.order("-createdAt")
                .findObjects(new FindListener<Account>() {
                    @Override
                    public void done(List<Account> object, BmobException e) {
                        if (e == null) {
                            if (object != null && object.size() > 0) {
                                Toast.makeText(RegisterActivity.this, "该账号已存在，请检查您输入的电话号码", Toast.LENGTH_SHORT).show();
                                if (loadingDialog != null)
                                    loadingDialog.close();
                            } else {
                                employeeRegister(employee, account);
                            }
                        } else {
                            Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            if (loadingDialog != null)
                                loadingDialog.close();
                        }
                        btnRegisterEmployee.setEnabled(true);
                        btnRegisterStudent.setEnabled(true);
                    }
                });
    }

    private void employeeRegister(Employee employee, Account account) {
        new Thread(() -> employee.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                runOnUiThread(() -> {
                    if (e == null) {
                        createAccount(account);
                    } else {
                        btnRegisterEmployee.setEnabled(true);
                        Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        if (loadingDialog != null) {
                            loadingDialog.close();
                        }
                    }
                });

            }
        })).start();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2021 && resultCode == 2021) {
            school = (School) data.getSerializableExtra("school");
            if (school != null)
                tvStudentSchool.setText(school.getSchool_name());
        }
    }

}
